package de.damontools.AWoLoWA;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.damontools.AWoLoWA.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class WiFiCheck extends Activity implements OnClickListener {
	private static final String TAG = "WiFiWoL";
	@SuppressWarnings("unused")
	private Button buttonStart, buttonStop, buttonSendWoLString,
			buttonSendWoLByte, buttonCheckClient;
	@SuppressWarnings("unused")
	private EditText editMAC, editIP;
	private Spinner editSSID;
	private static TextView txtStatus;
	@SuppressWarnings("unused")
	private BroadcastReceiver receiver;
	@SuppressWarnings("unused")
	private Button buttonScan;
	static WifiManager wifi;
	private static List<String> ssidList  = new ArrayList<String>();

	private static String macString;
	private static int ssidInt;
	private static String ssidString;
	private static String statusString = "";

	public static final int PORT = 9;

	private String ip = "255.255.255.255";
	@SuppressWarnings("unused")
	private InetAddress in = null;
	static final String PREFS_NAME = "AutoWoLPrefs";
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	private static Date date;
	private boolean ServiceisRunning = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
			checkWifis();
		init();
	}

	/**
	 * Check the available Wifis
	 */
	@SuppressWarnings("null")
	private void checkWifis() {
		wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//		List<WifiConfiguration> wifilist = null;
		// if Request a scan for access points. Returns immediately. The
		// availability of the results is made known later by means of an
		// asynchronous event sent on completion of the scan.
		// Returns true if the operation succeeded, i.e., the scan was initiated
//		if(ssidList.size() < 1){
			
//			wifilist = wifi.getConfiguredNetworks();
		for (WifiConfiguration wifilist: getWifi().getConfiguredNetworks()) {
//			for(int i = 0 ; i < getWifi().getConfiguredNetworks().size(); i++){
				ssidList.add(wifilist.SSID.toString().replace("\"", ""));
			}
//		}
		editSSID = (Spinner) findViewById(R.id.editSSID);
		Log.d(TAG, "size of ssidlisT: "+ssidList.size());
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, ssidList);
		
		editSSID.setAdapter(adapter);
		
//		Log.d("WifiLog", "size of ssidlist: " + ssidList.size());
	}

	protected void onStop() {
		super.onStop();
		SavePreferences("SSID", editSSID.getSelectedItemPosition());
		// ssidPosition = editSSID.getSelectedItemPosition();
		SavePreferences("MAC", editMAC.getText().toString());
		SavePreferences("STATUS", txtStatus.toString());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		SavePreferences("SSID", editSSID.getSelectedItemPosition());
		ssidInt = editSSID.getSelectedItemPosition();
		SavePreferences("MAC", editMAC.getText().toString());
		SavePreferences("STATUS", txtStatus.toString());
	}

	/**
	 * init GUI-elements
	 */
	private void init() {
		buttonStart = (Button) findViewById(R.id.buttonStart);
		buttonStop = (Button) findViewById(R.id.buttonStop);
		buttonSendWoLString = (Button) findViewById(R.id.buttonSendWoLString);

		txtStatus = (TextView) findViewById(R.id.txtStatusOutput);

		editMAC = (EditText) findViewById(R.id.editMAC);

		buttonStart.setOnClickListener(this);
		buttonStop.setOnClickListener(this);
		buttonSendWoLString.setOnClickListener(this);

//		sharedPreferences = getPreferences(MODE_PRIVATE);
		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		editor = sharedPreferences.edit();

		LoadPreferences();

	}

	/**
	 * @return the wifi
	 */
	public static WifiManager getWifi() {
		return wifi;
	}

	/**
	 * @param wifi
	 *            the wifi to set
	 */
	public static void setWifi(WifiManager _wifi) {
		wifi = _wifi;
	}

	private void LoadPreferences() {
		// SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
		ssidInt = sharedPreferences.getInt("SSID", 1);
		macString = sharedPreferences.getString("MAC", "00-00-00-00-00-00");
		editSSID.setSelection(ssidInt);
		editMAC.setText(macString);
		txtStatus.setText(statusString);

	}

	private void SavePreferences(String key, String value) {
		// SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
		// SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

	private void SavePreferences(String key, int value) {
		// SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
		// SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putInt(key, value);
		editor.commit();

		Log.d("WiFiWoL", "SSIDposition: " + editSSID.getSelectedItemPosition());
		Log.d("WiFiWoL", "SSID: " + editSSID.getItemAtPosition(value).toString());
		ssidString = editSSID.getItemAtPosition(value).toString();
	}

	@SuppressWarnings("unused")
	public void onClick(View src) {
		SavePreferences("SSID", editSSID.getSelectedItemPosition());
		SavePreferences("MAC", editMAC.getText().toString());
		SavePreferences("STATUS", txtStatus.toString());
		ssidInt = editSSID.getSelectedItemPosition();
		macString = editMAC.getText().toString();
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		try {
			in = InetAddress.getByName(ip);
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}

		switch (src.getId()) {
			case R.id.buttonStart:
				if (!ServiceisRunning) {
					Log.d(TAG, "onClick: starting service");
					startService(new Intent(this, WiFiCheckService.class));
					setTxtStatus("Service started");
					ServiceisRunning = true;
				}
				break;
			case R.id.buttonStop:
				if (ServiceisRunning) {
					Log.d(TAG, "onClick: stopping service");
					stopService(new Intent(this, WiFiCheckService.class));
					setTxtStatus("Service stopped");
					ServiceisRunning = false;
				}
				break;
			case R.id.buttonSendWoLString:
				Log.d(TAG, "onClick: sending WoL-signal over " + ssidInt + " to " + macString);
				WakeOnLan.wakeup(macString);
				// setTxtStatus("sending WoL...");
				break;
		}
	}

	/**
	 * @param strMAC
	 *            the strMAC to set
	 */
	public static void setMAC(String strMAC) {
		WiFiCheck.macString = strMAC;
	}

	public static String getMAC() {
		return macString;
	}

	public static String getSSID() {
		return ssidString;
	}

	/**
	 * @param strSSID
	 *            the strSSID to set
	 */
	public static void setStrSSID(String strSSID) {
		ssidString = strSSID;
	}

	public static String getTxtStatus() {
		return txtStatus.getText().toString();
	}

	public static void setTxtStatus(String status) {
		date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		statusString = df.format(date) + ": " + status + "\n" + statusString;
		txtStatus.setText(statusString);
		// WiFiCheck.txtStatus = txtStatus;
	}
}